#coding: utf-8
class BuildingController < ApplicationController
  before_filter :user_authorize
  before_filter :sys_before_log
  
  def getAllBuildingUnits
    start = params[:start].to_i
    limit = params[:limit].to_i
    query = params[:query]
    query = query.to_s
    #等于nil是给管理介面使用的。
      #buildings = Building.where(:all,:conditions=>["number like ? OR name like ?",query,query])
      buildings = Building.name_like query

    buildingsNow = buildings.paginate start,limit
    jsonStr="{totalProperty:"+buildings.length.to_s+",root:"+buildingsNow.to_json()+"}"

    puts jsonStr
    render :text=>jsonStr, :layout=>false
  end

  def getHighBuildingUnits
    query = params[:query]
    
    puts query

    #等于nil是给管理介面使用的。
    if query == nil
      buildings = Building.all
    elsif   query.length < 1 #小于负1是给combobox查询所有内容使用的这时它可能是“”，所以是空的，但不是nil
      buildings = Building.where("is_locked = 0 and sub_type = '高层'")
    elsif  query.length>0
      query = "%"+query+"%"
      buildings = Building.where("(number like ? OR name like ?) AND sub_type = '高层' ",query,query)
    end
    jsonStr="{totalProperty:"+buildings.length.to_s+",root:"+buildings.to_json()+"}"
    puts jsonStr
    render :text=>jsonStr, :layout=>false
  end
  
  def createBuildingUnit
    buildings = Building.where("number = ?",params[:number])
    if buildings.length > 0
      info = "已经有相同编号的楼座单元存在，请从新输入编号。"
    else
      building = Building.new
      building.number = params[:number]
      building.name = params[:name]
      building.sub_type = params[:sub_type]
      building.save
      info = "成功"
    end
    result = "{success:true,info:'#{info}'}"
    render :text=>result, :layout=>false
  end

  def getBuildingUnitById
    
    puts params[:building_id]
    building = Building.find(params[:building_id])
    rootStr = building.to_json()
    jsonStr = "{root:["+rootStr+"]}"
    render :text=>jsonStr, :layout=>false
  end
  
  def editBuildingUnit
    @buildingId = params[:building_id]
  end

  def updateBuildingUnit
    
    buildings = Building.where("number = ? AND id <> ?",params[:number],params[:id])
    if buildings.length > 0
      info = "已经有相同编号的楼座单元存在，请从新输入编号。"
    else
      building = Building.find(params[:id])
      building.number = params[:number]
      building.name = params[:name]
      building.sub_type = params[:sub_type]
      building.save
      info = "成功"
    end
    result = "{success:true,info:'#{info}'}"
    render :text=>result, :layout=>false
  end

  def buildingUnitLock
    building = Building.find(params[:building_id])
    if building.id >1
      if building.is_locked == 1
        building.is_locked = 0
      else
        building.is_locked = 1
      end
      building.save
    end
    info = "成功"
    result = "{success:true,info:'#{info}'}"
    render :text=>result, :layout=>false
  end
end
